package com.sea.supply.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;

import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.operate.entity.RelatedSku;
import com.sea.operate.service.RelatedSkuService;
import com.sea.product.entity.Product;
import com.sea.product.service.ChannelService;
import com.sea.product.service.ProductService;
import com.sea.supply.entity.ProductPrice;
import com.sea.supply.entity.Receive;
import com.sea.supply.service.ProductPriceService;
import com.sea.supply.service.SupplierService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/supply/report")
public class SupplyReportController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private ProductPriceService productPriceService;
    @Autowired
    private SupplierService supplierService;

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/produce/main")
    public String main(Model model) {
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/supply/report/produce/main";
    }
    @RequestMapping("/price/main")
    public String latestMain(Model model) {
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/supply/report/price/main";
    }



    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/getProduce")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Product product) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Product> list = productService.getProduce(product);
        PageInfo<Product> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/getLatestPrice")
    public AjaxTableReturn getLatestPrice(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                          @RequestParam(value = "offset", defaultValue = "0") int start,
                                          ProductPrice productPrice) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<ProductPrice> list = productPriceService.getLatestPrice(productPrice);
        PageInfo<ProductPrice> page = new PageInfo<ProductPrice>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @RequestMapping(value = "/exportPrice", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response,ProductPrice productPrice) {
        List<ProductPrice> list = productPriceService.getLatestPrice(productPrice);
        String[] title = {"渠道","SKU","最新含税价格供应商","最新含税价格","税率","利润测算含税价格","更新时间"};
        String fileName = "供应商报价信息" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "供应商报价信息";
        String[][] content = new String[list.size()][7];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            ProductPrice map = list.get(i);
            content[i][0] = map.getProductChannelName();
            content[i][1] = map.getProductSku();
            content[i][2] = map.getProductSupplierName();
            content[i][3] = map.getProductPriceCny()+"";
            content[i][4] = map.getProductPercent()+"";
            content[i][5] = map.getProductUnitPrice()+"";
            content[i][6] = map.getModifyTime().substring(0,10);

        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    /**
     * 导出待收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void exportShipped(HttpServletRequest request, HttpServletResponse response,  Product product) {
        List<Product> list = productService.getProduce(product);
        String[] title = {"渠道","SKU","产品名称","采购在产","国内仓库存","海外仓库存","实际在途(FBA)","实际在途(海外仓)","实际在途(海外仓-FBA)"};
        String fileName = "在途报表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "在途报表";
        String[][] content = new String[list.size()][9];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Product obj = list.get(i);
            content[i][0] = obj.getProductPropertyName();
            content[i][1] = obj.getProductSku();
            content[i][2] = obj.getProductName();
            content[i][3] = obj.getProduceNumber()+"";
            content[i][4] = obj.getWareNumber()+"";
            content[i][5] = obj.getStockNumber()+"";
            content[i][6] = obj.getCreateNumber()+"";
            content[i][7] = obj.getCreateWareNumber()+"";
            content[i][8] = obj.getCreatePortNumber()+"";

        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
